//
//  BHCircleDetailViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/9.
//

import UIKit
import IQKeyboardManagerSwift

class BHCircleDetailViewController: BHBaseViewController {    
    
    lazy var navigarionBar: BHCircleDetailNavigationBar = {
        let view = BHCircleDetailNavigationBar.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.begainY)
        view.more_btn.setImage(UIImage.init(named: "bh_circle_detail_nav_more"), for: .normal)
        view.delegate = self
        return view
    }()
    
    lazy var header_view: BHCircleDetailBannerHeaderView = {
        let view = BHCircleDetailBannerHeaderView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.width+15)
        view.delegate = self
        return view
    }()
    
    lazy var reviewBottomView: BHCircleDetailReviewBottomView = {
        let view = BHCircleDetailReviewBottomView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.height-UIScreen.safeBottomHeight-49, width: UIScreen.width, height: UIScreen.safeBottomHeight+49)
        view.delegate = self
        return view
    }()
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight-UIScreen.safeBottomHeight-49)
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .color_f8f8f8
        return view
    }()
    
    lazy var reviewTextView: BHCircleReviewTextView = {
        let view = BHCircleReviewTextView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height))
        view.delegate = self
        return view
    }()
    
    lazy var popView: BHDialogView = {
        let view = BHDialogView.loadFromXib()
        view.delegate = self
        view.pop_traling.constant = 20
        return view
    }()
    
    lazy var serviceManager: BHCircleDetailServiceManager = {
        let manager = BHCircleDetailServiceManager.init()
        return manager
    }()
    
    var circleId: String = ""
    fileprivate var detailModel: BHCircleDetailInfoModel = BHCircleDetailInfoModel.init()
    fileprivate var reviewArray: [BHCircleReviewModel] = []
    
 
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.serviceManager.circleId = self.circleId
        self.bh_navigationBar.removeFromSuperview()
        self.regiseterCell()
        
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.navigarionBar)
        self.view.addSubview(self.reviewBottomView)
        self.view.addSubview(self.reviewTextView)
        self.tableView.tableHeaderView = self.header_view
        
        self.view.addSubview(self.popView)

        self.obeserveNet()
        
        SVProgressHUD.show()
        self.serviceManager.loadDetailService()
        self.serviceManager.loadReviewService(page: 1)
        
        self.tableView.addRefresh { [weak self] in
            self?.page = 1
            self?.serviceManager.loadDetailService()
            self?.serviceManager.loadReviewService(page: 1)
        }
        
        self.tableView.addloadMore { [weak self] in
            self?.page += 1
            self?.serviceManager.loadReviewService(page: self?.page ?? 1)
        }
    }
    

    private func regiseterCell() {
        self.tableView.regiseterNib(nibName: "BHCircleDetailInfoCell")
        self.tableView.regiseterNib(nibName: "BHCircleDetailPlaceInfoCell")
        self.tableView.regiseterNib(nibName: "BHCircleDetailReviewInfoCell")
        self.tableView.regiseterNib(nibName: "BHCircleDetailReplyCell")
        self.tableView.regiseterNib(nibName: "BHCircleReplayBottomCell")
    }

}
extension BHCircleDetailViewController: BHDialogViewDelegate {
    func didDialogSelectIndex(type: Int) {
        if type == 0 { // 分享
            BHShareTool.showShareMenuView { platform in
                BHShareTool.share_weblink(title: self.detailModel.title, desText: self.detailModel.content, thumImage: "bh_app_share_icon", linkUrl: String.share_circleDetail_url+self.circleId, platForm: platform)
            }
        }
        if type == 1 { // 删除 | 举报
            if self.detailModel.userId == BHMeUserInfoModel.shared.userId { // 自己发的,删除
                BHCommonTool.showCustomAlertWith(showVC: self, title: "提示", message: "是否确认删除圈子？", okBtn: "再想想", cancel: "立即删除") { (cancel) in
                    if cancel == false {
                        SVProgressHUD.show()
                        self.serviceManager.deleteCircleService(circleId: self.circleId)
                    }
                }
            }else {
                BHRouter.shared.bh_report(type: 2, businessId: self.circleId)
            }
        }
    }
}


// MARK: 跳转关联的地方
extension BHCircleDetailViewController {
    func relationEntry() {
        if self.detailModel.relationType == 1 { // 场馆
            if self.detailModel.relationId.isEmpty == true {
                return
            }
            BHRouter.shared.bh_goStadiumDetail(stadium: self.detailModel.relationId)
        }
        
        if self.detailModel.relationType == 2 { // 赛事
            BHRouter.shared.bh_goGameDetail(gameId: self.detailModel.relationId)
        }
        if self.detailModel.relationType == 3 { // 趣玩
            BHRouter.shared.bh_goFunDetail(funId: self.detailModel.relationId)
        }
    }
}

//MARK: 触发评论
extension  BHCircleDetailViewController: BHCircleDetailReviewBottomViewDelegate {
    func didTapReviewAct() {
        self.reviewTextView.becomeActive(false)
    }
}

// MARK: 播放视频
extension BHCircleDetailViewController: BHCircleDetailBannerHeaderViewDelegate {
    func circleDetailPlayVideo() {
        let model = BHImageOrVideoModel.init()
        model.videoUrl = self.detailModel.circleUrlList[0]
        if model.videoUrl?.isEmpty == false {
            BHMediaTool.previewVideo(model: model)
        }
    }
}

extension BHCircleDetailViewController: BHCircleReviewTextViewDelegate {
    func reviewTextViewPublishReview(text: String, reply: Bool,replyModel: BHCircleReviewModel?) {
        if text.isEmpty == true {
            BHToast.toast(text: "请输入您的评论")
        }else {
            if reply == false { // 发表圈子的评论
                SVProgressHUD.show()
                self.serviceManager.reviewCircleService(content: text)
            }else { // 回复评论
                SVProgressHUD.show()
                self.serviceManager.replyReviewService(reviewId: replyModel!.reviewId, content: text)

            }
        }
    }
}

extension BHCircleDetailViewController: BHCircleDetailNavigationBarDelegate {
    func didSelectNavigationBarType(type: Int) {
        if type == 0 { // 返回点击
            self.navigationController?.popViewController(animated: true)
        }
        if type == 1 { //
            self.popView.show()
        }
        if type == 2 { // 关注
            self.attentionOrNot()
        }
        if type == 3 { // 进入主页
            BHRouter.shared.bh_goPersonalHome(userId: self.detailModel.userId)
        }
    }
}

extension BHCircleDetailViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.reviewArray.count == 0 {
            return 2
        }
        return 1+self.reviewArray.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 2
        }else {
            if self.reviewArray.count == 0 {
                return 0
            }
            let model = self.reviewArray[section-1]
            if model.replys.count <= 2 {
                return 2+model.replys.count
            }else {
                if model.reviewFlag == true { // 展开了
                    return 2+model.replys.count
                }else {
                    return 4
                }
            }
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                return self.detailModel.contentHeight+self.detailModel.title_height+58
            }else {
                if self.detailModel.relationId.isEmpty == true {
                    return 0
                }
                return BHCircleDetailPlaceInfoCell.cellHeight
            }
        }else {
            if self.reviewArray.count == 0 {
                return 0
            }
            let model = self.reviewArray[indexPath.section-1]
            if indexPath.row == 0 {
                return model.cellHeight
            }else {
                if model.reviewFlag == true || model.replys.count <= 2{ // 展开
                    if indexPath.row == model.replys.count+1 {
                        return model.bottomHeight
                    }else {
                        let replayModel = model.replys[indexPath.row-1]
                        return replayModel.replyCellHeight
                    }
                }else {
                    if indexPath.row == 3 {
                        return model.bottomHeight
                    }else {
                        let replayModel = model.replys[indexPath.row-1]
                        return replayModel.replyCellHeight
                    }
                }
            }
        }
    }
   
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return BHCircleDetailReviewSecView.secHeight
        }else {
            return CGFloat.leastNormalMagnitude
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
}

extension BHCircleDetailViewController: UITableViewDelegate {
  
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 {
            let view = BHCircleDetailReviewSecView.loadFromXib()
            view.review_count_label.text = "全部评论·\(self.detailModel.commentNum)"
            view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: BHCircleDetailReviewSecView.secHeight)
            return view
        }else {
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleDetailInfoCell", for: indexPath) as! BHCircleDetailInfoCell
                cell.model = self.detailModel
                cell.like_btn.addBtnAction(action: {[weak self] (_) in
                    self?.circlelikeOrNotService()
                }, for: .touchUpInside)
                return cell
            }else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleDetailPlaceInfoCell", for: indexPath) as! BHCircleDetailPlaceInfoCell
                cell.model = self.detailModel
                cell.place_backView.addViewAction {[weak self] (_) in
                    self?.relationEntry()
                }
                cell.clipsToBounds = true
                return cell
            }
        }else {
            return self.cellForReview(indexPath: indexPath)
        }
    }
}


extension BHCircleDetailViewController {
    func cellForReview(indexPath: IndexPath) -> UITableViewCell {
        let model = self.reviewArray[indexPath.section-1]
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleDetailReviewInfoCell", for: indexPath) as! BHCircleDetailReviewInfoCell
            cell.model = model
            cell.iconImgView.addViewAction { (_) in
                BHRouter.shared.bh_goPersonalHome(userId: model.reviewerId)
            }
            // 回复
            cell.replyBtn.addBtnAction(action: {[weak self] (_) in
                self?.reviewTextView.reviewer = model
                self?.reviewTextView.becomeActive(true)
            }, for: .touchUpInside)
            
            cell.deleteSelfReviewBlock = {[weak self] in // 自己发布的，删除
                SVProgressHUD.show()
                self?.serviceManager.deleteReviewService(reviewOrReplyId: model.reviewId)
            }
            cell.reportOtherReviewBlock = { // 他人发布的，举报
                BHRouter.shared.bh_report(type: 1, businessId: model.reviewId)
            }
            return cell
        }else {
            if model.replys.count <= 2 {
                if indexPath.row == model.replys.count+1 {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleReplayBottomCell", for: indexPath) as! BHCircleReplayBottomCell
                    cell.more_replayBtn.isHidden = true
                    cell.more_reply_view.isHidden = model.replys.count == 0
                    return cell
                }else {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleDetailReplyCell", for: indexPath) as! BHCircleDetailReplyCell
                    let replayModel = model.replys[indexPath.row-1]
                    cell.model = replayModel
                    cell.deleteSelfReviewBlock = { [weak self] in // 自己发布的，删除
                        SVProgressHUD.show()
                        self?.serviceManager.deleteReviewService(reviewOrReplyId: replayModel.reviewId)
                    }
                    cell.reportOtherReviewBlock = { // 他人发布的，举报
                        BHRouter.shared.bh_report(type: 1, businessId: replayModel.reviewId)
                    }
                    return cell
                }
                
            }else {
                if model.reviewFlag == true {
                    if indexPath.row == model.replys.count+1 {
                        let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleReplayBottomCell", for: indexPath) as! BHCircleReplayBottomCell
                        cell.more_replayBtn.setTitle("展开全部\(model.replys.count)条回复>", for: .normal)
                        cell.more_reply_view.isHidden = false
                        cell.more_replayBtn.isHidden = false
                        cell.more_replayBtn.isSelected = model.reviewFlag
                        cell.didSelectReplyActBlock = {[weak self] flag in
                            model.reviewFlag = flag
                            self?.tableView.reloadData()
                        }
                        return cell
                    }else {
                        let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleDetailReplyCell", for: indexPath) as! BHCircleDetailReplyCell
                        let replayModel = model.replys[indexPath.row-1]
                        cell.model = replayModel
                        cell.deleteSelfReviewBlock = { [weak self] in // 自己发布的，删除
                            SVProgressHUD.show()
                            self?.serviceManager.deleteReviewService(reviewOrReplyId: replayModel.reviewId)
                        }
                        cell.reportOtherReviewBlock = { // 他人发布的，举报
                            BHRouter.shared.bh_report(type: 1, businessId: replayModel.reviewId)
                        }
                        return cell
                    }
                }else {
                    if indexPath.row == 3 {
                        let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleReplayBottomCell", for: indexPath) as! BHCircleReplayBottomCell
                        cell.more_replayBtn.setTitle("展开全部\(model.replys.count)条回复>", for: .normal)
                        cell.more_reply_view.isHidden = false
                        cell.more_replayBtn.isHidden = false
                        cell.more_replayBtn.isSelected = model.reviewFlag
                        cell.didSelectReplyActBlock = {[weak self] flag in
                            model.reviewFlag = flag
                            self?.tableView.reloadData()
                        }
                        return cell
                    }else {
                        let cell = tableView.dequeueReusableCell(withIdentifier: "BHCircleDetailReplyCell", for: indexPath) as! BHCircleDetailReplyCell
                        let replayModel = model.replys[indexPath.row-1]
                        cell.model = replayModel
                        cell.deleteSelfReviewBlock = { [weak self] in // 自己发布的，删除
                            SVProgressHUD.show()
                            self?.serviceManager.deleteReviewService(reviewOrReplyId: replayModel.reviewId)
                        }
                        cell.reportOtherReviewBlock = { // 他人发布的，举报
                            BHRouter.shared.bh_report(type: 1, businessId: replayModel.reviewId)
                        }
                        return cell
                    }
                }
            }
        }
    }
}

extension BHCircleDetailViewController {
    func obeserveNet()  {
        
        // 详情回调
        self.serviceManager.detailResponseForMainBlock = {[weak self] (success,errorMsg,model) in
            self?.tableView.endRefresh()
            SVProgressHUD.dismiss()
            if success == true {
                self?.detailModel = model
                self?.navigarionBar.model = model
                if model.resourceType == 1 {
                    self?.header_view.imageUrls = model.circleUrlList
                }else {
                    if model.circleUrlList.count != 0 {
                        self?.header_view.videoUrl = model.circleUrlList[0]
                    }
                }
                if model.userId == BHMeUserInfoModel.shared.userId { // 自己发的,删除
                    self?.popView.popType = 1
                }else {
                    self?.popView.popType = 0
                }
                
//
                self?.tableView.reloadData()
            
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
        // 评论列表回调
        self.serviceManager.detailResponseForReviewBlock = {[weak self] (success,errorMsg,total, array) in
            self?.tableView.endLoading()
            if success == true {
                if self?.page == 1 {
                    self?.tableView.endLoadWithNoMoreData(false)
                    if self?.reviewArray.count != 0 {
                        self?.reviewArray.removeAll()
                    }
                }
                
                self?.reviewArray.append(contentsOf: array)
                self?.tableView.reloadData()

                if self?.reviewArray.count ?? 0 >= total {
                    self?.tableView.endLoadWithNoMoreData(true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
        // 发表评论或回复评论的回调
        self.serviceManager.reviewOrReplyResultActBlock = { [weak self] (success,errorMsg) in
            SVProgressHUD.dismiss()
            if success == true {
                self?.reviewTextView.publishComplete()
                BHToast.toast(text: "评论成功")
                self?.page = 1
                self?.serviceManager.loadReviewService(page: 1)
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
        // 删除评论的回调
        self.serviceManager.deleteCircleOrReplyBlock = { [weak self] (success,errorMsg) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "动态已删除")
                NotificationCenter.default.post(name: NSNotification.Name.init(String.deleteSelfCircleKey), object: nil)
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    self?.navigationController?.popViewController(animated: true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
        // 删除评论的回调
        self.serviceManager.deleteReviewOrReplyBlock = { [weak self] (success,errorMsg) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "评论已删除")
                self?.page = 1
                self?.serviceManager.loadReviewService(page: 1)
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
    
    func attentionOrNot()  {
        SVProgressHUD.show()
        BHCommonService.attentionOrNotService(type: 5, businessId: self.detailModel.userId) { (success, errorMsg) in
            SVProgressHUD.dismiss()
            if success == true {
                if self.detailModel.attentionFlag == 1 { // 已关注。取消
                    self.detailModel.attentionFlag = 0
                    BHToast.toast(text: "关注已取消")
                }else {
                    self.detailModel.attentionFlag = 1
                    BHToast.toast(text: "已关注")
                }
                self.navigarionBar.model = self.detailModel;

            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
    func circlelikeOrNotService() {
        SVProgressHUD.show()
        BHCommonService.circleLikeOrNot(circleId: self.circleId) { (success, errorMsg) in
            SVProgressHUD.dismiss()
            if success == true{
                if self.detailModel.likeFlag == 1 { // 已经是点赞了，此时取消
                    self.detailModel.likeFlag = 0
                    self.detailModel.supportNumber -= 1
                }else {
                    self.detailModel.likeFlag = 1
                    self.detailModel.supportNumber += 1
                }
                self.tableView.reloadData()
            }else {
                BHToast.toast(text: errorMsg) 
            }
        }
    }
    
    
}
